<?php

namespace App\Http\Controllers;


use Illuminate\Support\Facades\Validator;

class ApiController extends Controller
{
    /**
     * api 验证
     * @param $data
     * @param $rules
     * @param array $messages
     */
    public function validator($data, $rules, $messages = array())
    {
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            foreach ($validator->messages()->all() as $message) {
                self::error($message);
            }
        }
    }

    /**
     * json success
     * @param $data
     */
    public static function success($data, $message = '操作成功')
    {
        $return = array(
            'response' => '100',
            'message' => $message,
            'data' => self::outputFilter((array)$data)
        );

        header('Content-type: application/json');
        echo json_encode($return);
        exit;
    }

    /**
     *
     * json error
     * @param $message
     * @param int $code
     */
    public static function error($message, $code = 105)
    {
        $return = array(
            'response' => $code,
            'message' => $message,
        );

        header('Content-type: application/json');
        echo json_encode($return);
        exit;
    }

    /**
     *
     * 输出过滤
     * @param $data
     * @return mixed
     */
    public static function outputFilter($data)
    {
        array_walk_recursive($data, function (&$item, $key) {
            if (is_bool($item)) {
                $item = (true === $item) ? 'true' : 'false';
            } elseif (is_null($item)) {
                $item = '';
            } elseif (is_string($item)) {
                //	$item = iconv("GBK","UTF-8//TRANSLIT//IGNORE",$item);
            } elseif (is_numeric($item)) {
                $item = strval($item);
            }
        });

        return $data;
    }
}
